<template>
  <div class="container">
    <div class="box">
      <ProductItem
        class="item"
        v-for="(v, k) of products"
        :key="k"
        :href="`/products/${v.ID}`"
        :src="v.ImgUrl"
        :title="v.Name"
        :description="v.Description"
        :price="v.Price"
      />
    </div>
    <n-pagination
      class="page"
      v-if="pagination.totalCount"
      v-model:page="pagination.page"
      v-model:page-size="pagination.pageSize"
      :page-count="pagination.totalCount"
      @update:page="pagination.onChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { watchEffect, reactive } from "vue";
import { NPagination } from "naive-ui";
import { useProducts } from "@/hooks/Product";
import ProductItem from "@/components/product/ProductItem.vue";

const props = defineProps<{
  keywords?: string;
  category?: string;
}>();

const { total, products, getAllProducts } = useProducts();

const pagination = reactive({
  page: 1,
  pageSize: 12,
  totalCount: 0,
  onChange: async (page: number) => {
    await getAllProducts({ keywords: props.keywords, page });
  },
});

watchEffect(async () => {
  await getAllProducts({
    category: props.category,
    keywords: props.keywords,
    page: pagination.page,
  });
  pagination.totalCount = Math.ceil(total.value / pagination.pageSize);
});
</script>

<style lang="less" scoped>
.container {
  margin: 0 1em;

  .box {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    gap: 1em;

    .item {
      background-color: white;
      border: 1px solid var(--border-color);
      overflow: hidden;
    }
  }

  .page {
    margin-top: 1em;
    display: flex;
    justify-content: center;
  }
}
</style>
